{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ec062807",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "05c99b92",
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensorboardX import SummaryWriter"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "a8f0f4d7",
   "metadata": {},
   "outputs": [],
   "source": [
    "writer1 = SummaryWriter('./runs/test1')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "8f7c72be",
   "metadata": {},
   "outputs": [],
   "source": [
    "writer2 = SummaryWriter()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "1e97211c",
   "metadata": {},
   "outputs": [],
   "source": [
    "writer3 = SummaryWriter(comment='test2')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "75abd3c6",
   "metadata": {},
   "outputs": [],
   "source": [
    "#在DOS环境下运行以下代码\n",
    "#tensorboard --logdir=D:/动手学PyTorch深度学习建模与应用/ch09/runs/\n",
    "#然后再在浏览器中打开本地服务器，监听端口为6006，http://localhost:6006/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "eab878f7",
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensorboardX import SummaryWriter\n",
    "\n",
    "writer = SummaryWriter('runs/scalar')\n",
    "for i in range(10):\n",
    "    writer.add_scalar('指数', 3**i, global_step=i)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "37cf5acd",
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensorboardX import SummaryWriter\n",
    "import cv2 as cv\n",
    "\n",
    "writer = SummaryWriter('runs/image')\n",
    "for i in range(1, 4):\n",
    "    writer.add_image('倒计时',cv.cvtColor(cv.imread('./image/{}.jpg'.format(i)),cv.COLOR_BGR2RGB),global_step=i,dataformats='HWC')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "c9a11b59",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from tensorboardX import SummaryWriter\n",
    "\n",
    "writer = SummaryWriter('runs/embedding')\n",
    "writer.add_histogram('正态分布中心化', np.random.normal(0, 1, 1000), global_step=1)\n",
    "writer.add_histogram('正态分布中心化', np.random.normal(0, 2, 1000), global_step=50)\n",
    "writer.add_histogram('正态分布中心化', np.random.normal(0, 3, 1000), global_step=100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f6b5e8cf",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "dd822a32",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "torch.Size([1, 3, 224, 224])\n",
      "(1, 1000) 452\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "import numpy as np\n",
    "from torchvision import models,transforms\n",
    "from PIL import Image\n",
    "from tensorboardX import SummaryWriter\n",
    "\n",
    "vgg16 = models.vgg16() # 这里下载预训练好的模型\n",
    "\n",
    "transform_2 = transforms.Compose([\n",
    "    transforms.Resize(224),\n",
    "    transforms.CenterCrop(224),\n",
    "    transforms.ToTensor(),\n",
    "    \n",
    "    transforms.Lambda(lambda x: torch.index_select(x, 0, torch.LongTensor([2, 1, 0]))),\n",
    "    transforms.Lambda(lambda x: x*255),\n",
    "    transforms.Normalize(mean = [103.939, 116.779, 123.68],\n",
    "                          std = [ 1, 1, 1 ]),\n",
    "])\n",
    "\n",
    "cat_img = Image.open('./image/1.jpg')\n",
    "vgg16_input=transform_2(cat_img)[np.newaxis]# 因为pytorch的是分批次进行的，所以我们这里建立一个批次为1的数据集\n",
    "print(vgg16_input.shape)\n",
    "\n",
    "#开始前向传播，打印输出值\n",
    "raw_score = vgg16(vgg16_input)\n",
    "raw_score_numpy = raw_score.data.numpy()\n",
    "print(raw_score_numpy.shape, np.argmax(raw_score_numpy.ravel()))\n",
    "\n",
    "#将结构图在tensorboard进行展示\n",
    "with SummaryWriter(log_dir='./runs/graph', comment='vgg16') as writer:\n",
    "    writer.add_graph(vgg16, (vgg16_input,))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "d981a6c6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "warning: Embedding dir exists, did you set global_step for add_embedding()?\n"
     ]
    }
   ],
   "source": [
    "import torchvision\n",
    "from tensorboardX import SummaryWriter\n",
    "\n",
    "writer = SummaryWriter('runs/vector')\n",
    "mnist = torchvision.datasets.MNIST('./', download=False)\n",
    "writer.add_embedding(\n",
    "    mnist.data.reshape((-1, 28 * 28))[:30,:],\n",
    "    metadata=mnist.targets[:30],\n",
    "    label_img = mnist.data[:30,:,:].reshape((-1, 1, 28, 28)).float() / 255,\n",
    "    global_step=0\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "04ed4fe8",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from torch.utils.tensorboard import SummaryWriter\n",
    "\n",
    "np.random.seed(20200910)\n",
    "labels = np.random.randint(2, size=100)\n",
    "predictions = np.random.rand(100)\n",
    "\n",
    "writer = SummaryWriter()\n",
    "writer.add_pr_curve('P-R曲线', labels, predictions, 0)\n",
    "writer.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "28cd223c",
   "metadata": {},
   "outputs": [],
   "source": [
    "#动手练习：可视化模型参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "a65685ac",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from torch.utils.tensorboard import SummaryWriter\n",
    "\n",
    "np.random.seed(10)\n",
    "writer = SummaryWriter('runs/Loss_Accuracy')\n",
    "\n",
    "for n_iter in range(100):\n",
    "    writer.add_scalar('损失/训练集', np.random.random(), n_iter)\n",
    "    writer.add_scalar('损失/测试集', np.random.random(), n_iter)\n",
    "    writer.add_scalar('准确率/训练集', np.random.random(), n_iter)\n",
    "    writer.add_scalar('准确率/测试集', np.random.random(), n_iter)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
